package com.interview.item.javabase.distributed_transaction;

import ch.qos.logback.core.spi.PreSerializationTransformer;
import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.jdbc.AtomikosDataSourceBean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Author:zxh
 * @Description:
 * @Date: 2020/9/6
 * @Modified By:
 */
public class AtomikosJTATest {

    //使用atomikos对数据源做一层代理封装
    public static AtomikosDataSourceBean getAtomikos(String dbName){
        Properties properties = new Properties();
        properties.setProperty("url","");
        properties.setProperty("user","root123");
        properties.setProperty("password","password");

        //使用Atomikos封装com.mysql.jdbc.jdbc2.optional.MysqlXADataSource
        AtomikosDataSourceBean sourceBean = new AtomikosDataSourceBean();
        sourceBean.setUniqueResourceName(dbName);
        sourceBean.setXaDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource");
        sourceBean.setXaProperties(properties);
        return sourceBean;
    }

    public static void main(String[] args) throws SQLException {
        AtomikosDataSourceBean ds1 = getAtomikos("db_user");
        AtomikosDataSourceBean ds2 = getAtomikos("db_account");

        Connection connection1= null;
        Connection connection2 = null;
        PreparedStatement statement1= null;
        PreparedStatement statement2 = null;
        //初始化了一个类似于管理器的
        UserTransactionImp userTransactionImp = new UserTransactionImp();

        //开启事务
        //userTransactionImp.begin();

        //执行db1的事务
         connection1 = ds1.getConnection();
         statement1 = connection1.prepareStatement("sql", Statement.RETURN_GENERATED_KEYS);
         statement1.setString(1,"zhulangshi");
         statement1.executeUpdate();//执行SQL不提交

        //执行db2的事务
        connection2 = ds2.getConnection();
        statement2 = connection2.prepareStatement("sql", Statement.RETURN_GENERATED_KEYS);
        statement2.setString(1,"zhulangshi");
        statement2.executeUpdate();//执行SQL不提交

        //两阶段提交
        //userTransactionImp.commit();





        //执行db2的事务
    }
}
